package com.gz.mylife.app;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.view.MenuItemCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.po.ChoosePhotoInfo;
import com.gz.mylife.util.DialogUtils;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.AddPhotoPanel;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.AddPhotoPanel.OnPanelItemSelectedListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.UploadEvaluationContentListener;
import com.zl.smartmall.library.listener.UploadEvaluationPictureListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;


public class ProductCommentIssue extends BaseActivity implements TextWatcher, OnClickListener, OnPanelItemSelectedListener {

	private static final String TAG = ProductCommentIssue.class.getSimpleName();
	private static final int CONTENT_LENGTH_LIMIT = 500;
	private int mCurrentQueuePosition;
	private String mImgTempCachePath;
	private String mImgCapturePath;
	private StringBuilder mSBuilder;
	private ContentResolver mContentResolver;
	private DisplayImageOptions mImageOptions;
	private List<ChoosePhotoInfo> mUploadPhotoInfoQueue;
	private UploadEvaluationContentListener mUploadEvaluationContentListener;
	private UploadEvaluationPictureListener mUploadEvaluationPictureListener;
	private SparseArray<ChoosePhotoInfo> mChoosePhotoInfoQueue;
	
	private AddPhotoPanel mAddPhotoPanel;
	private ImageView[] mThumbnails;
	private TextView mTvHint500;
	private EditText mEtContent;
	private View mRootView;
	private OfflineDialog mOfflineDialog;
	private ProgressDialog mProgressDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mRootView = getLayoutInflater().inflate(R.layout.activity_product_comment_issue, null);
		setContentView(mRootView);

		mContentResolver = getContentResolver();
		mImgCapturePath = mImgTempCachePath = Tools.obtainDirPath(getApplicationContext(), Constants.FOLDER_IMG_TEMP_CACHE);
		mChoosePhotoInfoQueue = new SparseArray<ChoosePhotoInfo>();
		mSBuilder = new StringBuilder();
		mUploadPhotoInfoQueue = new ArrayList<ChoosePhotoInfo>();
		initListener();
		initImageOptions();
		
		mThumbnails = new ImageView[]{
				(ImageView) findViewById(R.id.iv_picture1),
				(ImageView) findViewById(R.id.iv_picture2),
				(ImageView) findViewById(R.id.iv_picture3),
				(ImageView) findViewById(R.id.iv_picture4)
		};
		for(ImageView view : mThumbnails) {
			view.setOnClickListener(this);
		}
		
		findViewById(R.id.btn_submit).setOnClickListener(this);
		findViewById(R.id.btn_pic_from_camera).setOnClickListener(this);
		findViewById(R.id.btn_pic_from_album).setOnClickListener(this);
//		mActionBar.setTitle("发表评价");
		setActionbarTitle("发表评价", true);
		mAddPhotoPanel = (AddPhotoPanel) getLayoutInflater().inflate(
				R.layout.add_photo_panel, 
				(ViewGroup) mRootView,
				false);
		mAddPhotoPanel.setOnPanelItemSelectedListener(this);
		mAddPhotoPanel.setVisibility(View.VISIBLE);
		mTvHint500 = (TextView) findViewById(R.id.tv_hint_500);
		mEtContent = (EditText) findViewById(R.id.et_content);
		mEtContent.addTextChangedListener(this);
		mEtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(CONTENT_LENGTH_LIMIT)});
		mOfflineDialog = (OfflineDialog) getLayoutInflater().inflate(R.layout.offline_dialog, null);
		
		CrashHandler.d(TAG, "商品id = " + getIntent().getIntExtra("productId", 0));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.product_comment_issue, menu);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_submit), 
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_submit:
//			if(mProgressDialog == null) {
//				mProgressDialog = DialogUtils.showProgressDialog(
//						this, null, "评价提交中, 请稍等", true, false, null);
//			}else {
//				mProgressDialog.show();
//			}
//			if(mChoosePhotoInfoQueue.size() > 0) {
//				uploadPicture();
//			}else {
				submit();
//			}
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		mTvHint500.setText("还可以输入" + (CONTENT_LENGTH_LIMIT - mEtContent.getText().toString().length()) + "个字");
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.iv_picture1:
			thumbnailClickEvent(0);
			break;

		case R.id.iv_picture2:
			thumbnailClickEvent(1);
			break;

		case R.id.iv_picture3:
			thumbnailClickEvent(2);
			break;

		case R.id.iv_picture4:
			thumbnailClickEvent(3);
			break;
			
		case R.id.btn_submit:
			break;
			
		case R.id.btn_pic_from_album://选择图片
			intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_ALBUM);
			break;
		
		case R.id.btn_pic_from_camera://选择照相机
			mImgCapturePath = mImgTempCachePath + "/capture-" + System.currentTimeMillis() + ".jpg";
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra("scale", true);
			intent.putExtra("noFaceDetection", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(mImgCapturePath)));
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA);
			break;
			
//		case R.id.action_view_publish:
//			if(mChoosePhotoInfoQueue.size() > 0) {
//				uploadPicture();
//			}else {
//				uploadContent();
//			}
//			break;
		}
	}

	@Override
	public void onItemSelected(int itemId) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (itemId) {
		case ITEM_ID_ALBUM:
			intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_ALBUM);
			break;

		case ITEM_ID_CAMERA:
			mImgCapturePath = mImgTempCachePath + "/capture-" + System.currentTimeMillis() + ".jpg";
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra("scale", true);
			intent.putExtra("noFaceDetection", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(mImgCapturePath)));
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA);
			break;
			
		case ITEM_ID_CANCEL:
			break;
		}
		
		((ViewGroup) mRootView).removeView(mAddPhotoPanel);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Define.ACTIVITY_CODE_PICTURE_FROM_ALBUM:
			handlePictureFromAlbum(resultCode, data);
			break;
			
		case Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA:
			handlePictureFromCamera(resultCode, data);
			break;
		}
	}
	
	private void handlePictureFromAlbum(int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if(mChoosePhotoInfoQueue.size() >= 4) {
				ToastUtils.showToast(this, "亲 , 最多上传4张图片");
				return;
			}
			Cursor cursor = null;
			try {
				Uri uri = data.getData();
				String[] projection = {MediaColumns.DATA};
				cursor = mContentResolver.query(uri, projection, null, null, null);
		        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		        String photoPath = null;
		        if(cursor.moveToFirst()) {
		        //最后根据索引值获取图片路径
		        	photoPath = cursor.getString(column_index);
		        	photoPath = mImgTempCachePath + photoPath.substring(photoPath.lastIndexOf("/"));
			        CrashHandler.d(TAG, "相片路径 = " + photoPath);
					photoPath = Tools.saveBitmapAndGetPath(this,
							photoPath, uri);
		        }
		     
				if (!TextUtils.isEmpty(photoPath)) {
					ChoosePhotoInfo photoInfo = new ChoosePhotoInfo();
					photoInfo.setPath(photoPath);
					photoInfo.setUrl("file://" + photoPath);
					preview(photoInfo);
				}
		        
			} catch (OutOfMemoryError e) {
				CrashHandler.e(e);
			
			} finally {
				if(cursor != null) 
					 cursor.close();
			}
		}
	}
	
	private void handlePictureFromCamera(int resultCode, Intent data) {
		if(resultCode == RESULT_OK) {
			if(mChoosePhotoInfoQueue.size() >= 4) {
				ToastUtils.showToast(this, "亲 , 最多上传4张图片");
				return;
			}
			mImgCapturePath = Tools.saveBitmapAndGetPath(this, mImgCapturePath);
			if (!TextUtils.isEmpty(mImgCapturePath)) {
				ChoosePhotoInfo photoInfo = new ChoosePhotoInfo();
				photoInfo.setPath(mImgCapturePath);
				photoInfo.setUrl("file://" + mImgCapturePath);
				preview(photoInfo);
			}
		}
	}
	
	private void initListener() {
		mUploadEvaluationContentListener = new UploadEvaluationContentListener() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				if(mProgressDialog == null) {
					mProgressDialog = DialogUtils.showProgressDialog(
							ProductCommentIssue.this, null, "评价提交中, 请稍等", true, false, null);
				}else {
					mProgressDialog.show();
				}
			}
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ProductCommentIssue.this, "评价失败, 请重试");
				mCurrentQueuePosition = 0;
				dismissProgressDialog();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				ToastUtils.showToast(ProductCommentIssue.this, Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				dismissProgressDialog();
				finish();
			}
		};
		
		mUploadEvaluationPictureListener = new UploadEvaluationPictureListener() {
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				if(mProgressDialog == null) {
					mProgressDialog = DialogUtils.showProgressDialog(
							ProductCommentIssue.this, null, "评价提交中, 请稍等", true, false, null);
				}else {
					mProgressDialog.show();
				}
			}
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ProductCommentIssue.this, "评价失败, 请重试");
				mCurrentQueuePosition = 0;
				dismissProgressDialog();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				dismissProgressDialog();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(ProductCommentIssue.this, Define.MSG_NO_NETWORK);
				dismissProgressDialog();
			}
			
			@Override
			public void onResponseSuccess(int width, int height, String imageUrl,
					String uploadString) {
				// TODO Auto-generated method stub
				mSBuilder.append(uploadString + "|");
				mCurrentQueuePosition++;
				if(mCurrentQueuePosition < mUploadPhotoInfoQueue.size()) {
					ISmartMall.getInstance().uploadEvaluationPicture(getIntent().getIntExtra("productId", 0), mUploadPhotoInfoQueue.get(mCurrentQueuePosition).getPath(), this);
					
				}else {
					uploadContent();
				}
			}
		};
	}
	
	private void dismissProgressDialog() {
		if(mProgressDialog != null && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}
	}
	
	private void initImageOptions(){
		mImageOptions = new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.color.transparent)
        .showImageOnFail(R.color.transparent)
        .showImageForEmptyUri(R.color.transparent)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
        .build();
	}
	
	private void preview(ChoosePhotoInfo photoInfo) {
		ImageLoader.getInstance().displayImage(
				photoInfo.getUrl(), 
//				mThumbnails[mCurrentSelectedThumbnailItem], 
				mThumbnails[mChoosePhotoInfoQueue.size()], 
				mImageOptions);
//		mChoosePhotoInfoQueue.put(mCurrentSelectedThumbnailItem, photoInfo);
		mChoosePhotoInfoQueue.put(mChoosePhotoInfoQueue.size(), photoInfo);
	}
	
	private void thumbnailClickEvent(int item) {//选好图片之后，点击图片预览大图
//		mCurrentSelectedThumbnailItem = item;
//		((ViewGroup) mRootView).addView(mAddPhotoPanel);
		if(mChoosePhotoInfoQueue.get(item) != null) {
			ArrayList<String> url = new ArrayList<String>();
			for(int i = 0; i < mChoosePhotoInfoQueue.size(); i++) {
				int key = mChoosePhotoInfoQueue.keyAt(i);
				url.add(mChoosePhotoInfoQueue.get(key).getUrl());
			}
			Intent intent = new Intent(getApplicationContext(), HDPictureBrowse.class);
			intent.putStringArrayListExtra("picture", url);
			intent.putExtra("position", item);
			startActivity(intent);
		}
	}
	
	private void submit() {
		if(TextUtils.isEmpty(mEtContent.getText().toString())) {
			ToastUtils.showToast(this, "请输入评价内容");
			return;
		}
		if(mChoosePhotoInfoQueue.size() > 0) {
			uploadPicture();
			
		}else {
			uploadContent();
		}
	}

	private void uploadContent() {
		
		ISmartMall.getInstance().uploadEvaluationContent(
				getIntent().getIntExtra("productId", 0), 
				mEtContent.getText().toString(), 
				mSBuilder.length() == 0 ? "" : mSBuilder.substring(0, mSBuilder.length() - 1),
				mUploadEvaluationContentListener);
	}
	
	private void uploadPicture() {
		// TODO Auto-generated method stub
		for(int i = 0; i < 4; i++) {
			if(mChoosePhotoInfoQueue.get(i) != null) {
				mUploadPhotoInfoQueue.add(mChoosePhotoInfoQueue.get(i));
			}
		}
		
		for(ChoosePhotoInfo photo : mUploadPhotoInfoQueue) {
			CrashHandler.d(TAG, "path = " + photo.getPath());
		}
		
		ISmartMall.getInstance().uploadEvaluationPicture(
				getIntent().getIntExtra("productId", 0), 
				mUploadPhotoInfoQueue.get(mCurrentQueuePosition).getPath(), 
				mUploadEvaluationPictureListener);
	}

}
